#coding:utf-8
import json
import tornado
import tornado.web
import tornado.httpserver
import tornado.options
from tornado.options import define,options

define ("port",default=8888,type=int)

"""
参考
https://blog.csdn.net/buster2014/article/details/54137519
#
"""


class PingHandler(tornado.web.RequestHandler):

    def initialize(self):
        self.port = 6739
        self.host = "localhost"
    def set_default_headers(self):
        # 需要关闭跨站问题
        self.set_header("Access-Control-Allow-Origin", "*")
        # origin_url = self.request.headers.get('Origin')
        # self.set_header("Access-Control-Allow-Origin", origin_url)
        # self.set_header("Access-Control-Allow-Credentials", "true")
        # self.set_header("Access-Control-Allow-Headers", "x-requested-with,token")
        self.set_header("Access-Control-Allow-Methods", "DELETE, POST, GET, OPTIONS")
        self.set_header("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With")
        # self.set_header("Access-Control-Max-Age", 1000)
        # self.set_header("Content-type", "application/json")
    async def options(self):
        # no body
        self.set_status(204)
        return 
    #     self.finish()

    async def get(self):
        
        info = self.get_argument("info",None)
        self.write('{"status":0,"msg":"Request Success@@"}')
        #website =  self.get_argument("website",None)
class ReceiveDataHandle(tornado.web.RequestHandler):

    def set_default_headers(self):
        self.set_header("Access-Control-Allow-Origin", "*")
        self.set_header("Access-Control-Allow-Methods", "DELETE, POST, GET, OPTIONS")
        self.set_header("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With")
        # origin_url = self.request.headers.get('Origin')
        # self.set_header("Access-Control-Allow-Origin", origin_url)
        # self.set_header("Access-Control-Allow-Credentials", "true")
        # self.set_header("Access-Control-Allow-Headers", "x-requested-with,token")
        # self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
        # self.set_header("Access-Control-Max-Age", 1000)
        # self.set_header("Content-type", "application/json")

    async def get(self):
        self.write('{"status":-1,"msg":"Not supported \"GET\" method"}')
    async def options(self):
        # no body
        self.set_status(204)
        return 
    #     self.finish()
    async def post(self):

        try:
            data = self.request.body
            if isinstance(data,bytes):
                data = data.decode(encoding = "utf-8")
            print("data=>\n{}".format(json.loads(data)))
            self.write('{"code":200,"msg":"Success,I got data "}')
        except Exception as e:
            self.write('{"code":-1,"msg":"Parse data error "}')
            print("RecieveHandler error ,{}".format(e))
        


class Application(tornado.web.Application):

    def __init__(self):
        # super().__init__(handlers=handlers, default_host=default_host, transforms=transforms, **settings)
        handlers=[
            (r"/ping",PingHandler),
            (r"/send",ReceiveDataHandle)
        ]
        settings = dict()
        tornado.web.Application.__init__(self,handlers,settings)


def create_server():
    tornado.options.parse_command_line()
    server = tornado.httpserver.HTTPServer(Application())
    server.listen(options.port)
    print("server running : {}:{}".format("http://localhost",options.port))
    tornado.ioloop.IOLoop.instance().start()

if __name__ =="__main__":
    create_server()
        

